import { useLocalStorageState, useRequest } from 'ahooks'
import React, { FC, useEffect, useState } from 'react'
import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { SideBar, Tag, Image, ImageViewer, Divider } from 'antd-mobile'
import { LikeOutline, EditSOutline, HeartOutline, UserOutline, EnvironmentOutline, ClockCircleOutline, FireFill } from 'antd-mobile-icons'
import dayjs from 'dayjs'


import './Detail.scss'
import { addcollectoneAPI, addlikeoneAPI, changetravelsAPI, delcollectoneAPI, dellikeoneAPI, getcollectlistAPI, getlikelistAPI, getpinglistAPI, gettravelbyidAPI } from '../../api/api'
import MyHeader from '../../components/MyHeader'
import { baseURL } from '../../api/request'
import { useSelector } from 'react-redux'
import { useComment } from '../../hooks/common'
import { ShowMsg } from '../../utils/message'

const Detail: FC = () => {
  const router = useNavigate()
  const [query] = useSearchParams()
  const params = useParams()
  const [tdata, setTdata] = useState<any>(null)
  const [index, setIndex] = useState<number>(0)
  const [visible, setVisible] = useState<boolean>(false)
  // 是否已收藏
  const [hasCollect, setHasCollect] = useState<boolean>(false)
  // 是否已点赞
  const [hasLike, setHasLike] = useState<boolean>(false)
  const { userInfo } = useSelector((state: any) => state.info)
  const [AppPhone, setAppPhone] = useLocalStorageState<string | number>('AppPhone')
  const { checkHashLogin } = useComment()
  const [pingsList, setPingsList] = useState(false)


  // 获取详情页的数据
  const getDetailData = useRequest(gettravelbyidAPI, {
    manual: true,
    onSuccess: (res: any) => {
      setTdata(res.result)

      changeTravelData.run({
        _id: params.id,
        hot: res.result.hot + 1
      })
    }
  })

  // 修改热度
  const changeTravelData = useRequest(changetravelsAPI, {
    manual: true,
  })

  // 点赞的列表 查询自己的点赞数据
  const getLikeListData = useRequest(getlikelistAPI, {
    manual: true,
    onSuccess: (res: any, body) => {
      setHasLike(!!res.result.length) // 1已经点赞 0没有点赞
    }
  })

  // 判断是否已经点赞
  const checkMineHasLike = () => {
    getLikeListData.run({
      tid: params.id,
      flag: true
    })
  }

  // 判断是否已经收藏
  const getCollectListData = useRequest(getcollectlistAPI, {
    manual: true,
    onSuccess: (res: any, body) => {
      setHasCollect(!!res.result.length)
    }
  })

  // 点赞
  const todoLike = () => {
    checkHashLogin(async () => {
      if (hasLike) {
        let res: any = await dellikeoneAPI({
          tid: params.id,
          phone: AppPhone
        })
        if (res.code == 200) {
          ShowMsg('取消点赞')
          // 修改后端
          changeTravelData.run({
            _id: params.id,
            hot: tdata.hot - 2,
            likes: tdata.likes - 1
          })
          // 修改前端
          setHasLike(false)
          tdata.hot -= 2
          tdata.likes = tdata.likes - 1
          setTdata({ ...tdata })
        }
      } else {
        // 没有点过赞
        let res: any = await addlikeoneAPI({
          tid: params.id,
          phone: AppPhone,
          travel: tdata,
          userInfo
        })
        if (res.code == 200) {
          // 点赞成功 修改后端
          changeTravelData.run({
            _id: params.id,
            hot: tdata.hot + 2,
            likes: (tdata.likes ? tdata.likes : 0) + 1
          })
          // 修改前端
          ShowMsg('点赞成功')
          setHasLike(true)
          tdata.hot += 2
          tdata.likes = (tdata.likes ? tdata.likes : 0) + 1
          setTdata({ ...tdata })
        }
      }
    })
  }

  // 收藏
  const todoCollect = () => {
    checkHashLogin(async () => {
      if (hasCollect) {
        let res: any = await delcollectoneAPI({
          tid: params.id,
          phone: AppPhone
        })
        if (res.code == 200) {
          ShowMsg('取消收藏')
          // 修改后端
          changeTravelData.run({
            _id: params.id,
            hot: tdata.hot - 3,
            collects: tdata.collects - 1
          })
          // 修改前端
          setHasCollect(false)
          tdata.hot -= 3
          tdata.collects = tdata.collects - 1
          setTdata({ ...tdata })
        }
      } else {
        // 没有收藏
        let res: any = await addcollectoneAPI({
          tid: params.id,
          phone: AppPhone,
          travel: tdata,
          userInfo
        })
        if (res.code == 200) {
          // 收藏成功 修改后端
          changeTravelData.run({
            _id: params.id,
            hot: tdata.hot + 3,
            collects: (tdata.collects ? tdata.collects : 0) + 1
          })
          // 修改前端
          ShowMsg('收藏成功')
          setHasCollect(true)
          tdata.hot += 3
          tdata.collects = (tdata.collects ? tdata.collects : 0) + 1
          setTdata({ ...tdata })
        }
      }
    })
  }

  useEffect(() => {
    getDetailData.run({
      _id: params.id
    })

    checkMineHasLike()

    getCollectListData.run({
      tid: params.id,
      flag: true
    })

  }, [])


  return (
    <div>
      <MyHeader title={query.get('title')} onClick={() => router(-1)}></MyHeader>

      <div className='detail-content'>
        {
          tdata &&
          <div key={tdata._id} className='detail-content-box'>
            <p className='detail-title'>{tdata.title}</p>
            <p className='detail-username'>
              <UserOutline />：
              {tdata.author?.username}
            </p>
            <p className='detail-address'>
              <EnvironmentOutline />：
              {tdata.address}
            </p>
            <p className='detail-date'>
              <ClockCircleOutline />：
              {dayjs(tdata.date).format("YYYY-MM-DD")}
            </p>
            <p className='detail-hot'>
              <FireFill />：
              热度：{tdata.hot}
            </p>
            {
              tdata.tags.map((v: any, n: any) => {
                return (
                  <Tag color='success' key={n} className="detail-tag">{v.label}</Tag>
                )
              })
            }
            <div className='detail-imgbox'>
              {
                tdata.imgs.length > 0 &&
                <div>
                  {
                    tdata.imgs.map((e: any, i: any) => {
                      return (
                        <Image
                          onClick={() => {
                            setIndex(i)
                            setTimeout(() => {
                              setVisible(true)
                            }, 1)
                          }}
                          src={e.url?.replace(/public/, baseURL)}
                          key={i}
                        />
                      )
                    })
                  }
                </div>
              }
            </div>
            <p className='content-detail'>{tdata.content}</p>
            <div className='detail-footer'>
              <span onClick={todoLike} style={{ color: hasLike ? "#f50" : '' }}>
                <LikeOutline />
                {tdata.likes ? '：' + tdata.likes : '：' + 0}
              </span>
              <span>
                <EditSOutline />
                {tdata.pings ? '：' + tdata.pings : '：' + 0}
              </span>
              <span onClick={todoCollect} style={{ color: hasCollect ? "#f50" : '' }}>
                <HeartOutline />
                {tdata.collects ? '：' + tdata.collects : '：' + 0}
              </span>
            </div>
          </div>
        }
      </div>
      {
        visible && <ImageViewer.Multi
          images={tdata.imgs.map((item: any) => {
            return item.url.replace(/public/, baseURL)
          })}
          visible={visible}
          defaultIndex={index}
          onClose={() => {
            setVisible(false)
          }}
        />
      }

      <div style={{ padding: '10px' }}>
        <div style={{ fontSize: '15px', fontWeight: '600' }}>
          评论
        </div>
        <Divider style={{ margin: '5px 0' }} />
        <div>
          1
        </div>
      </div>
    </div>
  )
}

export default Detail
